<template>
	<div>
		<!-- 查询条件 -->
		<el-row >
			<el-col :span="1" class="labelCol">
				<p class="labelText">任务状态:</p>
			</el-col>
			<el-col :span="3">
				<el-select v-model="taskStatus" size='small' placeholder="任务状态" clearable>
					<el-option v-for="item in  taskStatusCombo" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
			<el-col :span="1" class="labelCol">
				<p class="labelText">任务大类:</p>
			</el-col>
			<el-col :span="3">
				<el-select v-model="taskPtype" size='small' placeholder="任务大类" clearable @change="taskStatusChange">
					<el-option v-for="item in  taskPTypeCombo" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
			<el-col :span="1" class="labelCol">
				<p class="labelText">任务细类:</p>
			</el-col>
			<el-col :span="3">
				<el-select v-model="taskCtype" size='small' placeholder="任务细类" clearable>
					<el-option v-for="item in  taskCTypeCombo" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
			</el-col>
			<el-col :span="1" class="labelCol">
				<p class="labelText">选择人员:</p>
			</el-col>
			<el-col :span="3">
				<el-select v-model="deal" size='small' placeholder="处理人" clearable>
					<el-option v-for="item in  sa" :label="item.label" :value="item.value">
						<span style="float: left">{{ item.label }}</span>
						<span style="float: right; color: #FF0000; font-size: 13px">
							<el-tag type="danger">{{ item.sum }}</el-tag>
						</span>
					</el-option>
				</el-select>
			</el-col>

			<el-col :span="1" class="labelCol">
				<p class="labelText">任务标题:</p>
			</el-col>
			<el-col :span="3">
				<el-input size="small" style="width: 90%;" v-model="taskTitle" placeholder="任务标题"></el-input>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="1" class="labelCol">
				<p class="labelText">行政区域:</p>
			</el-col>
			<el-col :span="3">
				<el-select size="small" v-model="area" multiple placeholder="行政区域" clearable>
					<el-option v-for="item in  areaCombo " :label="item.label" :value="item.value"></el-option>
				</el-select>
			</el-col>
			<el-col :span="1" class="labelCol">
				<p class="labelText">VIN:</p>
			</el-col>
			<el-col :span="3">
				<el-input size="small" style="width: 90%;" v-model="vin" placeholder="VIN"></el-input>
			</el-col>
		
		</el-row>
		<el-row>
			<el-col :span="20" style="text-align:right;">
				<el-button size="small" type="primary" @click="queryTaskGrid">查询</el-button>
				</el-col>
				<el-col :span="4" style="text-align:right;" v-if="this.$data.queryCompanyId == this.$data.curCompanyId">
				<!-- 	<el-button size="small" type="primary" @click="exportExecl">导出</el-button> -->
					<el-button size="small" type="primary" @click="batch">任务处理</el-button>
					<el-button size="small" type="primary" @click="customTask">自定义任务</el-button>
			</el-col>
		</el-row>
		<!-- 查询条件 -->
		<!-- 任务表格 -->
		<el-row>
			<el-col :span="24">

				<el-table :data="taskGrid.dataList" border @selection-change="handleSelectionChange" :row-class-name="tableRowClassName" @row-dblclick="dbClick">
					<el-table-column type="selection" width="60">
					</el-table-column>
					<el-table-column label="类别" width="100">
						<template scope="scope">
							<el-tag type="primary">{{scope.row.typeName}}</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="日期" align="center" width="150">
						<template scope="scope">
							{{scope.row.expectDate}}
						</template>
					</el-table-column>
					<el-table-column prop="dealDate" label="任务完成时间" width="150">
					</el-table-column>
					<el-table-column prop="vin" label="车架号" width="240">
					</el-table-column>
					<el-table-column prop="plateNum" label="车牌号" width="140">
						<template scope="scope">
							<el-button type="text" v-on:click="plateNumQuery(scope.$index)"> {{scope.row.plateNum}}</el-button>
							<el-badge class="mark" :value="scope.row.cp" />
						</template>
					</el-table-column>
					<el-table-column prop="content" label="任务标题">
					</el-table-column>
					<el-table-column prop="status" label="任务状态" width="200" :formatter="statusFor">
					</el-table-column>
					<el-table-column prop="uname" label="处理人" width="80">
					</el-table-column>

				</el-table>
				<el-pagination small @current-change="handleCurrentChange" :current-page="CurentPage" :page-sizes="page.pageSizes" :page-size="page.pageSize" layout=" total,prev, pager, next" :total="taskGrid.total">
				</el-pagination>
			</el-col>
		</el-row>
		<!-- 任务表格 结束 -->

		<!-- 维系记录窗口-->
		<concat :rowData="rowData" :show="rowDataShow" v-if="rowDataShow" v-on:refresh="refresh"></concat>


			<!--自定义任务-->
		<el-dialog tittl="自定义任务" v-model="customTaskShow" size="tiny">
			<el-form :model="customTaskData" ref="customTaskForms" :rules="customTaskRule" label-width="100px">
				<el-col :span="24">
					<el-form-item label="提醒日期:" prop="expectDate" style="width: 250px;">
						<el-date-picker style="width:100%" v-model="customTaskData.expectDate" type="date" :editable=false placeholder="有效时间" size="small">
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="提醒内容:" prop="content">
						<el-input size="small" placeholder="请输入内容" v-model="customTaskData.content">
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="联系人:" prop="linkMan">
						<el-input size="small" placeholder="请输入内容" v-model="customTaskData.linkMan">
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="联系人电话:" prop="linkPhone">
						<el-input size="small" placeholder="请输入内容" v-model="customTaskData.linkPhone">
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="车牌号:" prop="plateNum">
						<el-input size="small" placeholder="请输入内容" v-model="customTaskData.plateNum">
						</el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="车架号:" prop="vin">
						<el-input size="small" placeholder="请输入内容" v-model="customTaskData.vin">
						</el-input>
					</el-form-item>
				</el-col>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="customTaskShow = false">取 消</el-button>
				<el-button type="primary" @click="saveTask">提 交</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
export default {
  computed: {},

  data: function() {
    return {
      curCompanyId: window.localStorage.getItem("companyId"),
      // 查询条件公司ID
      queryCompanyId: window.localStorage.getItem("companyId"),
      // 查询区域
      queryArea: "",
      // 查询品牌
      queryBrand: "",
      //查询条件行政区域
      area: [],
      //车架号
      vin: "",
      //xingzhengquyuxiala
      areaCombo: [],
      // 区域
      areaCombo2: [],
      // 品牌
      brandCombo: [],
      // 公司
      companyCombo: [],
      //自定义任务表单
      customTaskData: {
        expectDate: "",
        content: "",
        linkMan: "",
        linkPhone: "",
        plateNum: "",
        vin: "",
        saId: "",
        companyId: "",
        carId: "",
        typePcode: "zdy",
        typeCode: "zdy",
        isBack: "",
        status: 0,
        dealDate: "",
        contactId: "",
        assignId: "",
        assignName: ""
      },
      //自定义表单初始化
      TaskData: {
        expectDate: "",
        content: "",
        linkMan: "",
        linkPhone: "",
        plateNum: "",
        vin: "",
        saId: window.localStorage.getItem("uid"),
        companyId: "",
        carId: "",
        typePcode: "zdy",
        typeCode: "zdy",
        isBack: "",
        status: 0,
        dealDate: "",
        contactId: "",
        assignId: window.localStorage.getItem("uid"),
        assignName: window.localStorage.getItem("userName")
      },
      //自定义表单显示
      customTaskShow: false,
      //自定义表单检验规则
      customTaskRule: {
        linkMan: [
          {
            required: true,
            message: "请填写联系人",
            trigger: "blur"
          }
        ],
        linkPhone: [
          {
            required: true,
            message: "请填写联系人电话",
            trigger: "blur"
          }
        ],
        expectDate: [
          {
            type: "date",
            required: true,
            message: "请选择提醒时间",
            trigger: "blur"
          }
        ],
        content: [
          {
            required: true,
            message: "请填写提醒内容",
            trigger: "blur"
          }
        ],
        plateNum: [
          {
            required: true,
            message: "请填写车牌号",
            trigger: "blur"
          }
        ],
        vin: [
          {
            required: true,
            message: "请填写车架号",
            trigger: "blur"
          }
        ]
      },
      rowData: {},
      rowDataShow: false,
      tagListsShow: false,

      //手动拨号的手机号
      telephoneInput: "",
      callFormShow: false,
      pickerOptions1: {
        shortcuts: [
          {
            text: "一天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24);
              picker.$emit("pick", date);
            }
          },
          {
            text: "两天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 2);
              picker.$emit("pick", date);
            }
          },
          {
            text: "三天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 3);
              picker.$emit("pick", date);
            }
          },
          {
            text: "四天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 4);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 7);
              picker.$emit("pick", date);
            }
          },
          {
            text: "两周后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 14);
              picker.$emit("pick", date);
            }
          },
          {
            text: "二十天后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 20);
              picker.$emit("pick", date);
            }
          },
          {
            text: "一个月后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 30);
              picker.$emit("pick", date);
            }
          },
          {
            text: "两月后",
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() + 3600 * 1000 * 24 * 60);
              picker.$emit("pick", date);
            }
          }
        ]
      },
      /*******查询客户相关数据↓*******/

      /*******查询客户相关数据↑*******/

      /******* 任务查询条件*******/
      plateNu: "",
      taskStatus: "0",
      page: this.page,
      CurentPage: 1,

      //任务标题
      taskTitle: "",
      /**************任务列表状态***************/
      taskGrid: {
        total: 30,
        dataList: []
      },

      multipleSelection: [],

      /********维护大类、维护小类字典 开始**/
      //级联选择的值

      sa: [],
      /********维护大类、维护小类字典 结束**/
      /********任务字典开始*********/
      taskPtype: "",
      taskCtype: "",
      deal: "",
      //任务状态
      taskStatusCombo: [],

      //任务大类
      taskPTypeCombo: [],
      // 任务细类
      taskCTypeCombo: [],
      //保险子类
      bxChild: [],
      //关爱子类
      gaChild: [],
      // 自定义子类
      qtChild: [],
      // 流失子类
      lsChild: [],
      //保养子类
      byChild: [],
      mrChild: [],
      zhChild: [],
      /***********任务字典结束****************/

      /***********流失方向字典结束****************/

      //维系窗口显示
      concatShow: false,
      //维系表单

      //勾选的任务
      changeId: []
    };
  },
  methods: {
    taskStatusChange: function(value) {
      debugger;
      switch (value) {
      	case "zh":
      	  this.$data.taskCTypeCombo = this.$data.zhChild;
          this.$data.taskCtype = "";
          break;
        case "by":
          this.$data.taskCTypeCombo = this.$data.byChild;
          this.$data.taskCtype = "";
          break;
        case "bx":
          this.$data.taskCTypeCombo = this.$data.bxChild;
          this.$data.taskCtype = "";
          break;
        case "ls":
          this.$data.taskCTypeCombo = this.$data.lsChild;
          this.$data.taskCtype = "";
          break;
        case "ga":
          this.$data.taskCTypeCombo = this.$data.gaChild;
          this.$data.taskCtype = "";
          break;
        case "qt":
          this.$data.taskCTypeCombo = this.$data.qtChild;
          this.$data.taskCtype = "";
          break;
        case "mr":
          this.$data.taskCTypeCombo = this.$data.mrChild;
          this.$data.taskCtype = "";
          break;
        default:
          this.$data.taskCTypeCombo = [];
          this.$data.taskCtype = "";
          break;
      }
    },
    //自定义任务
    customTask: function() {
      this.$data.customTaskShow = true;
      this.$data.customTaskData = Object.assign(
        this.$data.customTaskData,
        this.$data.TaskData
      );
    },
    //自定义任务保存
    saveTask: function() {
      debugger;
      this.$refs.customTaskForms.validate(
        function(valid) {
          if (valid) {
            var dates = this.$data.customTaskData.expectDate;
            if (dates == null || dates == "") {
              this.$data.customTaskData.expectDate = "";
            } else {
              this.$data.customTaskData.expectDate = this.moment(dates).format(
                "YYYY-MM-DD"
              );
            }
            this.$http
              .post(
                this.API_ROOT + "/crm/task/saveCustomer",
                this.$data.customTaskData,
                {
                  params: {}
                }
              )
              .then(
                resp => {
                  debugger;
                  if (resp.data.success) {
                    this.$message(resp.data.msg);
                    this.queryTaskGrid();
                    this.$data.customTaskShow = false;
                  } else {
                    this.$message.error(resp.data.msg);
                  }
                },
                resp => {}
              );
          }
          return false;
        }.bind(this)
      );
    },
    //维系记录插件保存后的回调
    refresh: function() {
      this.queryTaskGrid();
    },

    //任务状态转换
    statusFor: function(row, column) {
      if (row.status == 1) {
        return "已完成";
      } else if (row.status == 2) {
        return "已关闭";
      } else {
        if (
          row.expectDate <
          this.moment(new Date().toISOString()).format("YYYY-MM-DD")
        ) {
          return "任务已过期，请尽快处理！";
        } else {
          return row.statusName;
        }
      }
    },
    //查询
    conQuery: function() {
      this.$http({
        method: "GET",
        url: this.API_ROOT + "/crm/car/page", //url
        params: {
          //发送的参数
          key: "1", //查询类别
          value: this.$data.concatForm.vin //查询内容
        }
      }).then(
        function(resp) {
          //debugger;
          if ((resp.data.success = "查询成功！")) {
            this.$message("未查询到数据！");
            this.$data.coustomerShow = false;
            //this.$data.tableShow = false;
          } else {
            this.$data.coustomerShow = true;
            // es5写法
            this.$data.tableDataOrder = {
              total: 0,
              dataList: []
            };
            this.$data.tableData = resp.data;
            if (this.$data.tableData.CarInfo != undefined) {
              this.queryConcatGrid();
              //修改内容显示属性
              this.$data.tableShow = true;
            }
          }
        },
        function(error) {
          // error
          this.$message.error(resp.data.msg);
        }
      );
    },

    handleSelectionChange(val) {
      debugger;
      this.$data.multipleSelection = val;
      //给状态赋初值
      this.$data.changePlantU = true;
      //循环赋值（id）和判断（vin）
      for (var i = 0; i < val.length; i++) {
        this.$data.changeId[i] = val[i].id;
        if (val[i].vin != val[0].vin) {
          this.$data.changePlantU = false;
        }
      }
    },
    //点击批量处理
    batch: function() {
      debugger;
      var mmp = 0;
      if (this.$data.changePlantU == false) {
        this.$message.error("只能同时处理一辆车的任务！");
      } else {
        for (var i = 0; i < this.$data.multipleSelection.length; i++) {
          if (
            this.$data.multipleSelection[i].status == 1 ||
            this.$data.multipleSelection[i].status == 2
          ) {
            this.$message.error("该任务已完成或已关闭不可进行任务处理！");
            mmp = 1;
            break;
          }
        }
        if (mmp != 1) {
          this.$data.rowDataShow = false;
          this.addConcat(this.$data.multipleSelection);
        }
      }
    },

    tableRowClassName(row, index) {
      if (row.status > 0) {
        return "";
      } else {
        if (
          row.expectDate <
          this.moment(new Date().toISOString()).format("YYYY-MM-DD")
        ) {
          return "day-row";
        }
        return "";
      }
    },
    handleCurrentChange: function(page) {
      //debugger;
      this.$data.CurentPage = page;
      this.queryTaskGrid();
    },
    /***************打开维系记录窗口新增****************/
    addConcat: function(row) {
      debugger;
      this.$data.rowDataShow = true;
      this.$data.rowData = row;
    },

    /**************任务状态转换结束****************/

    /************************点击车牌号查询**************************************/
    /*************加载任务列表**********/
    plateNumQuery: function(a) {
      this.$data.CurentPage = 1;
      //debugger;
      this.$data.taskTitle = this.$data.taskGrid.dataList[a].plateNum;
      //this.queryTaskGrid();
      this.$http({
        method: "GET",
        url: this.API_ROOT + "/crm/task/page",
        params: {
          start: this.$data.CurentPage,
          limit: this.$data.page.pageSize,
          title: this.$data.taskTitle,
          pcode: this.$data.taskPtype,
          code: this.$data.taskCtype,
          deal: this.$data.deal,
          status: this.$data.taskStatus,
          platenum: this.$data.plateNum,
          //day: this.moment(new Date().toISOString()).format("YYYY-MM-DD HH:mm:ss"),
          companyId: this.$data.queryCompanyId
        }
      }).then(
        function(resp) {
          //success
          //debugger;
          resp.data.total = parseInt(resp.data.total);
          this.$data.taskGrid = resp.data;
          //debugger;
          this.$data.taskTitle = "";
        },
        function(error) {
          //error
        }
      );
    },

    /*************加载任务列表**********/
    queryTaskGrid: function() {
      var a = this.$data.area.join(",");
      this.$http({
        method: "GET",
        url: this.API_ROOT + "/crm/task/page",
        params: {
          start: this.$data.CurentPage,
          limit: this.$data.page.pageSize,
          title: this.$data.taskTitle,
          pcode: this.$data.taskPtype,
          code: this.$data.taskCtype,
          deal: this.$data.deal,
          status: this.$data.taskStatus,
          platenum: this.$data.plateNum,
          vin: this.$data.vin,
          day: this.moment(new Date().toISOString()).format(
            "YYYY-MM-DD HH:mm:ss"
          ),
          area: a,
          companyId: this.$data.queryCompanyId
        }
      }).then(
        function(resp) {
          //success
          //debugger;
          resp.data.total = parseInt(resp.data.total);
          this.$data.taskGrid = resp.data;
          this.$data.changePlantU = false;
          //debugger;
        },
        function(error) {
          //error
        }
      );
    },

    //加载查询条件分组的下拉数据
    groupComboF: function() {
      this.$data.sa = [];
      this.$data.deal = "";
      //加载分组
      this.$http
        .get(this.API_ROOT + "/crm/task/combo", {
          params: {
            //type: roleIds
            companyId: this.$data.queryCompanyId
          }
        })
        .then(
          response => {
            // success callback
            this.$data.sa = response.data;
          },
          response => {
            // error callback
          }
        );
    },
    dbClick: function(row, event) {
      if (this.$data.queryCompanyId != this.$data.curCompanyId) {
        return;
      }
      this.$data.rowDataShow = false;
      if (row.status == 1 || row.status == 2) {
        this.$message.error("该活动已完成或已关闭！");
      } else {
        this.addConcat(row);
      }
    },

   
   
    /********导出Execl**********/
    exportExecl: function() {
      var lodding = this.$loading({
        fullscreen: true,
        text: "正在生成导出数据，请稍候..."
      });
      var a = this.$data.area.join(",");
      this.$http({
        method: "GET",
        url: this.API_ROOT + "/crm/task/export",
        params: {
          start: this.$data.CurentPage,
          limit: this.$data.page.pageSize,
          title: this.$data.taskTitle,
          pcode: this.$data.taskPtype,
          code: this.$data.taskCtype,
          deal: this.$data.deal,
          status: this.$data.taskStatus,
          platenum: this.$data.plateNum,
          day: this.moment(new Date().toISOString()).format(
            "YYYY-MM-DD HH:mm:ss"
          ),
          area: a
        }
      }).then(
        function(resp) {
          lodding.close();
          if (resp.data.success) {
            window.location.href =
              this.API_ROOT +
              "/base/exp/xlsx?fileId=" +
              resp.data.data +
              "&&fileName=当天任务-" +
              this.moment().format("YYYYMMDDHHmmss") +
              "&&fileType=xlsx";
          }
          //debugger;
        },
        function(error) {
          this.$message({
            type: "error",
            message: "执行导出出错!"
          });
          //error
          lodding.close();
        }
      );
    },
    getNewDict: function(group) {
      //任务状态
      this.$http
        .get(this.API_ROOT + "/base/dict/combo/groups", {
          params: {
            group: "02030601,02030602,by,bx,ga,qt,ls,zh,mr"
          }
        })
        .then(
          response => {
            var combo = response.data;
            this.$data.taskStatusCombo = combo["02030601"];
            this.$data.taskPTypeCombo = combo["02030602"];
            this.$data.bxChild = combo["bx"];
            this.$data.gaChild = combo["ga"];
            this.$data.lsChild = combo["ls"];
            this.$data.zhChild = combo["zh"];
            this.$data.qtChild = combo["qt"];
            this.$data.byChild = combo["by"];
            this.$data.mrChild = combo["mr"];
          },
          response => {}
        );
    },

   
  },
  /******创建时运行*********/
  created: function() {
    //获取区域，品牌，公司信息
    this.groupComboF();
    this.getNewDict(); // 任务状态
    //加载任务列表
    this.queryTaskGrid();
  }
};
</script>
<style>

</style>